﻿using System;
using BusinessObject;
using Model;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace ViewLayer.Pages
{
    public partial class _Default : System.Web.UI.Page
    {
        User user;

        protected void Page_Load(object sender, EventArgs e)
        {
            user = (User)Session["User"];
            if (user == null)
            {
                Response.Redirect("../Account/Login.aspx");
            }

            if (!IsPostBack)
            {
                PopulateProjects();
            }
        }

        private void PopulateProjects()
        {
            grdProjetos.DataSource = ProjectUserBO.Instance.getProjectsByUser(user.Id);
            grdProjetos.DataBind();
        }

        protected void grdProjetos_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Project projeto = e.Row.DataItem as Project;

                (e.Row.FindControl("lblNome") as Label).Text = projeto.Nome;
                (e.Row.FindControl("lblDataInicio") as Label).Text = projeto.DataInicio.ToString("dd/MM/yyyy");
                (e.Row.FindControl("lblDataTermino") as Label).Text = projeto.DataFim.ToString("dd/MM/yyyy");
                (e.Row.FindControl("btnVisualizar") as Button).CommandArgument = projeto.Id.ToString();
                (e.Row.FindControl("btnRemover") as Button).CommandArgument = projeto.Id.ToString();
            }
        }

        protected void grdProjetos_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("Visualizar"))
            {
                Session["Project"] = ProjectBO.Instance.GetById(Convert.ToInt32(e.CommandArgument));
                Response.Redirect("../Pages/Projetos/InicioProjeto.aspx");
            }
            if (e.CommandName.Equals("Remover"))
            {
                ProjectBO.Instance.Delete(ProjectBO.Instance.GetById(Convert.ToInt32(e.CommandArgument)));
            }
        }

        protected void grdProjetos_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grdProjetos.PageIndex = e.NewPageIndex;
            grdProjetos.DataBind();
        }
    }
}